Lesson 6 - advanced exercise
For each scenario write code to solve it.
Scenario - Create a star field of 100 stars. Each star will have its own speed and position. The stars will travel from left to right and when they go off screen they will start at the far right with a new position and speed. (chosen randomly). To help you can use lists within lists. For example the list may look like [ [54,21,1], [43,102, 2],..... [x, y, speed] ]
# imports needed for pygame
import pygame
import sys
import os
import random
from pygame.locals import *
# set up some colours!
red = (255,0,0)
black = (0,0,0)
white = (255, 255, 255)
# set up game window
pygame.init()
window = pygame.display.set_mode((600,400))
pygame.display.set_caption("star field")
screen = pygame.display.get_surface()
# timer used to control animation
stars = []
timer = pygame.time.Clock()
# set up stars
for i in range(0,100):
x = random.randint(10,600)
y = random.randint(0,400)
speed = random.randint(1,5)
stars.append( [x,y,speed] )
# main loop
while True:
# deal with events.
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# clear the view
window.fill(black)
# draw the star field
for i in stars:
pygame.draw.circle(window, white, (i[0], i[1]), 0)
i[0] = i[0] - i[2]
# test for outside bounds
if i[0] <= 0:
i[0] = 600
i[1] = random.randint(0,400)
i[2] = random.randint(1,5)
pygame.display.update()
timer.tick(40)
Toggle answer
Scenario - Have a character which can move by using keys and have a baddie which is moving towards the character at all times. If they collide then the game is over. Overtime the score gets increased by 10 points.
# imports needed for pygame
import pygame
import sys
import os
from pygame.locals import *
# set up some colours!
blue = (0,0,255)
black = (0 ,0 ,0)
red = (255, 0 , 0)
# set up game window
pygame.init()
window = pygame.display.set_mode((600,400))
pygame.display.set_caption("bounce")
screen = pygame.display.get_surface()
# timer used to control animation
timer = pygame.time.Clock()
xpos = 30
ypos = 20
# add baddie
xbad = 500
ybad = 300
badspeed = 1
#
score = 0
# main loop
while True:
# deal with events.
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
key = pygame.key.get_pressed()
if key[K_LEFT]:
xpos-=5
if key[K_RIGHT]:
xpos+=5
if key[K_UP]:
ypos-=5
if key[K_DOWN]:
ypos+=5
# clear the view
window.fill(black)
# move the baddie toward the player
if xbad > xpos: xbad -= badspeed
elif xbad < xpos: xbad += badspeed
if ybad > ypos: ybad -= badspeed
elif ybad < ypos: ybad += badspeed
badspeed += 0.001
# draw the baddie
baddie = pygame.Rect((xbad, ybad, 20, 15))
pygame.draw.rect(window, red, baddie )
# draw the player
player = pygame.Rect((xpos, ypos, 20, 10))
pygame.draw.rect(window, blue, player )
if baddie.colliderect(player):
# end game
pygame.quit()
sys.exit()
pygame.display.update()
# add to score
score += 10
pygame.display.set_caption("score = " + str(score))
timer.tick(40)
Toggle answer